<template>
  <div id="sheet-container"></div>
</template>

<script setup lang="ts">
import { setupUniver } from '@/utils/setup-univer';
const emit = defineEmits(['cellSelection', 'deleteSheet', 'renameSheet']);
const { data } = defineProps<{ data?: any }>();
let univerApi: any = null;
let univerIns: any = null;
const initUniver = () => {
  const { univerAPI, univer } = setupUniver('sheet-container', {
    data,
    header: true,
    footer: true,
  });
  univerApi = univerAPI;
  univerIns = univer;
  console.log('univerjs', univerAPI.getActiveWorkbook().save());
};
// 方向键按下事件处理函数 或者tab和enter按下事件处理函数
// const handleKeyDown = async (event: KeyboardEvent) => {
//   await new Promise((resolve) => setTimeout(resolve, 100));
//   if (
//     event.key === 'ArrowUp' ||
//     event.key === 'ArrowDown' ||
//     event.key === 'ArrowLeft' ||
//     event.key === 'ArrowRight' ||
//     event.key === 'Tab' ||
//     event.key === 'Enter'
//   ) {
//     const activeWorkbook = univerApi.getActiveWorkbook();
//     const activeSheet = activeWorkbook?.getActiveSheet();
//     const activeCell = activeSheet?.getActiveCell();
//     if (activeCell) {
//       if (
//         activeCell._range.startRow == activeCell._range.endRow &&
//         activeCell._range.startColumn == activeCell._range.endColumn
//       ) {
//         const cellData = activeCell.getCellData();
//         emit('cellClick', {
//           row: activeCell._range.startRow,
//           column: activeCell._range.startColumn,
//           value: cellData.v,
//         });
//       }
//     }
//   }
// };
// const sheetEditEnded = async (params: any) => {
//   const { worksheet, row, column } = params;
//   console.log('editEnded', {
//     row,
//     column,
//     value: worksheet.getRange(row, column).getCellData().v,
//   });
//   await new Promise((resolve) => setTimeout(resolve, 100));
//   emit('editEnded', {
//     row,
//     column,
//     value: worksheet.getRange(row, column).getCellData().v,
//   });
// };
const selectionChanged = (params: any) => {
  if (params.selections.length !== 0) {
    emit('cellSelection', {
      startRow: params.selections[0].startRow,
      startColumn: params.selections[0].startColumn,
      endRow: params.selections[0].endRow,
      endColumn: params.selections[0].endColumn,
      sheetId: univerApi.getActiveWorkbook().getActiveSheet().getSheetId(),
      sheetName: univerApi.getActiveWorkbook().getActiveSheet().getSheetName(),
    });
  }
};
const deleteSheet = (param: any) => {
  const { worksheet } = param;
  emit('deleteSheet', {
    worksheet,
  });
};
const renameSheet = (param: any) => {
  const { worksheet, newName } = param;
  emit('renameSheet', {
    worksheet,
    newName,
    sheetId: worksheet.getSheetId(),
  });
};
onMounted(() => {
  initUniver();
  // univerApi.addEvent(univerApi.Event.SheetEditEnded, sheetEditEnded);
  univerApi.addEvent(univerApi.Event.SelectionChanged, selectionChanged);
  univerApi.addEvent(univerApi.Event.BeforeSheetDelete, deleteSheet);
  univerApi.addEvent(univerApi.Event.SheetNameChanged, renameSheet);
  // 监听键盘方向键按下事件
  // document.addEventListener('keyup', handleKeyDown);
});
onBeforeUnmount(() => {
  // univerApi.removeEvent(univerApi.Event.SheetEditEnded, sheetEditEnded);
  // univerApi.removeEvent(univerApi.Event.SelectionChanged, selectionChanged);
  univerApi?.dispose();
  univerIns?.dispose();
  univerApi = null;
  univerIns = null;
  // 移除键盘方向键按下事件监听器
  // document.removeEventListener('keyup', handleKeyDown);
});
defineExpose({
  getData: () => {
    return univerApi.getActiveWorkbook().save();
  },
  createWorkbook(excelData: any) {
    console.log('excelData-', excelData);
    if (univerApi) {
      univerApi.disposeUnit(univerApi.getActiveWorkbook().getId());
      univerApi.createWorkbook(excelData, {
        makeCurrent: true,
      });
    }
  },
  setSlection: (area: any, config: any) => {
    if (!univerApi) {
      return false;
    }
    const fWorkbook = univerApi.getActiveWorkbook();
    let fWorksheet: any = null;
    if (config.sheetId) {
      fWorksheet = fWorkbook.getSheetBySheetId(config.sheetId);
    } else {
      fWorksheet = fWorkbook.getSheets().find((v: any) => v.getIndex() === 0);
    }
    // 通过 FRange 设置选区 A1:B2
    const fRange = fWorksheet.getRange(area);
    fRange.activate();
    return true;
  },
  async export() {
    const fWorkbook = univerApi.getActiveWorkbook();
    const unitId = fWorkbook.getId();
    const file = await univerApi.exportXLSXByUnitIdAsync(unitId);
    console.log('file-', file);
  },
  async setProtection(
    formElement: any,
    options: {
      addProtection?: boolean; // 是否添加保护
      ruleIds?: any[]; // 规则ID
      permissionId?: string; // 权限ID
    } = {
      addProtection: true,
    },
    callback: any
  ) {
    const fWorkbook = univerApi.getActiveWorkbook();
    const fWorksheet = fWorkbook.getSheetBySheetId(formElement.sheetId);
    const fRange = fWorksheet.getRange(formElement.__position);
    const permission = univerApi.getPermission();
    if (!options.addProtection) {
      permission.removeRangeProtection(fWorkbook.getId(), fWorksheet.getSheetId(), options.ruleIds);
      return;
    }
    const { permissionId, ruleId } = await permission.addRangeBaseProtection(
      fWorkbook.getId(),
      fWorksheet.getSheetId(),
      [fRange]
    );
    callback && callback({ ruleId, permissionId });
  }
});
</script>

<style scoped lang="scss">
.univer-workbench-layout {
  .univer-sheet-bar.univer-relative.univer-flex.univer-h-full {
    display: none;
  }
}
</style>
